# -*- coding:utf-8 -*-  
from google.appengine.ext import webapp
import os 
from google.appengine.ext.webapp import template
#from datetime import timedelta
import datetime
import time
import random
from google.appengine.api import memcache
#from session import session
import md5
from google.appengine.api import mail
from model import *
class mywork():
    def render(self, name, data):
        self.temp = os.path.join(os.path.dirname(__file__), 'template', name)
        return template.render(self.temp, data)
    def dosession(self, key):
        requestkey = ''.join([key, str(time.time()), str(random.randint(0, 100000))])
        newkey = md5.md5(requestkey).hexdigest()
        return newkey
    def doheader(self,username, sessionkey, expiresday):
        '''expires=some day'''
        expires_date = datetime.datetime.utcnow() + datetime.timedelta(expiresday)
        expires_str = expires_date.strftime("%d %b %Y %H:%M:%S GMT")
        cookie = ''.join(['session', '=', sessionkey,'&' ,'username','=',username,'&','Expires','=',str(expires_str)])
        header = cookie.split('&')
        #{'Expires':expires_str,'Set-Cookie':cookie}
        return header
    def checkuser(self, username):
        user = userinfo.all().filter('username =', username).fetch(limit=1)
        if user:
            '''the username have been used'''
            return True
        else:
            return False
    def databasework(self, args):
        user = userinfo()
        user.username = args['username']
        user.password = args['password']
        user.gender = args['gender']
        user.collage = args['collage']
        user.school = args['school']
        user.major = args['major']
        user.email=args['email']
        user.put()
    
    def sendemail(self,m_subject,send_to,send_body):
        #if not mail.is_email_valid(send_to):
        # Return an error message...
        #    pass
        message = mail.EmailMessage()
        message.sender ='''haibolib@gmail.com'''
        message.subject=m_subject
        message.to=send_to
        message.html=send_body
        message.Send()
    def set_session(self,username,key,expire,method='cache'):
        '''expire deafult= one month'''
        if method == 'database':
            sess=session_db()
            sess.sessionkey=key
            sess.username=username
            sess.put()
        elif method == 'cache':
            memcache.set(username,key,expire)
    def get_session(self,username,method='cache'):
        if method == 'database':
            sess=session_db.all().filter('username =', username).get()
            key=sess.sessionkey
            return key.encode('ascii')
        elif method == 'cache':
            return memcache.get(username)
        

#@session()
class userlogin(webapp.RequestHandler,mywork):
    def get(self):
        out_html = mywork.render(self,'login.html', data={})
        self.response.out.write(out_html)
    def post(self):
        post_data = {'username':self.request.get('username'),
                   'password':self.request.get('password'),
                   }
        #self.session['user_name'] = post_data['username']
        #self.session['session'] = mywork.dosession(post_data['username'])
        
        myheader = mywork.doheader(self, self.get_session(post_data['username']), 365)
        for i in myheader:
            self.response.headers.add_header('Set-Cookie', i)
        self.response.headers.add_header('Expires','-1')
        self.response.out.write(mywork.render(self,'loginok.html', data={}))
        self.redirect('/user')
        
        
#@session()        
class register(webapp.RequestHandler,mywork):
    def get(self):
        out_html = mywork.render(self,'register.html', data={})
        self.response.out.write(out_html)
    def post(self):
        post_data = {'username':self.request.get('username'),
                   'password':self.request.get('password'),
                   'gender':self.request.get('gender'),
                   'collage':self.request.get('collage'),
                   'school':self.request.get('school'),
                   'major':self.request.get('major'),
                   'email':self.request.get('email')}
        if mywork.checkuser(self,post_data['username']):
            '''check if the username has been used'''
            self.response.out.write('''user name have been used''')
        else:
            '''save database and set cookies'''
            mywork.databasework(self,post_data)
            self.set_session(post_data['username'],self.dosession(post_data['username']), 120,)
            myheader = self.doheader(post_data['username'] ,self.get_session(post_data['username']),360)
            for i in myheader:
                self.response.headers.add_header('Set-Cookie', i)
            self.response.headers.add_header('Expires','-1')
            #self.sendemail('account has register succeed', post_data['email'], '''hello this is a test''')
            self.response.out.write(self.render('registerok.html',post_data))

class user(webapp.RequestHandler,mywork):
    def get(self):
        self.user_cookie=self.request.cookies
        self.username=self.user_cookie.get('username')
        self.sessionkey=self.user_cookie.get('session')
        if self.sessionkey == self.get_session(self.username,):
            self.response.out.write(self.render('user.html', {'uasrname':self.username}))
        else:
            #self.redirect('/login',)
            self.response.out.write(''.join([self.username,self.sessionkey,'\n',str(self.get_session(self.username))]))
        #self.response.out.write(str(self.user_cookie))
        #if self.user_cookie:
        #    dosome
        #else:
        #    self.redirect('/login')
            
         
